package rpg.update
{
	import rpg.Utils.GameUtils;
	import rpg.interfaces.IDestroy;
	import rpg.interfaces.IUpdate;
	import rpg.manager.SceneManager;

	public class Update implements IUpdate, IDestroy
	{
		public static const HIGHT : int = 2;
		public static const MIDDEN : int = 1;
		public static const LOW : int = 0;
		/**
		 * 更新帧数
		 */
		private var _frameRate : uint = 0;
		/**
		 * 更新优先级
		 */
		private var _priority : int;
		/**
		 * 更新间隔
		 */
		private var _frameInterval : uint = 0;
		/**
		 * 记录当前持续时间
		 */
		protected var frameElapsedTime : uint = 0;
		/**
		 * 是否需要检测更新
		 */
		private var checkUpdateable : Boolean = false;
		/**
		 * 是否销毁
		 */
		protected var _isDestroy : Boolean = false;

		/**
		 * 注册等级
		 */
		protected var registerdLevel : int;

		public function Update()
		{
			init();
		}

		/**
		 * 初始化 
		 * 
		 */
		protected function init() : void
		{

		}


		/**
		 * 如果是无限循环,责直接覆盖此函数
		 * 不是的话,责要设置生命周期
		 * @param delay
		 *
		 */
		public function update(delay : uint) : void
		{
		}

		public function checkUpdatable(elapsedTime : uint) : Boolean
		{
			if(!checkUpdateable)
			{
				return true;
			}
			frameElapsedTime += elapsedTime;

			if(frameElapsedTime >= _frameInterval)
			{
				frameElapsedTime -= _frameInterval;
				return true;
			}
			return false;
		}

		public function get frameRate() : uint
		{
			return _frameRate;
		}

		public function set frameRate(value : uint) : void
		{
			if(value <= 0 || value >= GameUtils.frameRate)
			{
				_frameRate = GameUtils.frameRate;
				checkUpdateable = false;
				return;
			}
			_frameRate = value;
			_frameInterval = 1000 / _frameRate;
			checkUpdateable = true;
		}

		public function get priority() : int
		{
			return _priority;
		}

		public function set priority(value : int) : void
		{
			_priority = value;
		}

		/**
		 *
		 * @param level   更新的等级,0低级,1中级,2高级
		 * @param priority优先级别
		 *
		 */
		public function registerd(registerdLevel : int = LOW, priority : int = 0) : void
		{
			if(SceneManager.getInstance().addUpdate(this, registerdLevel, priority))
			{
				this.registerdLevel = registerdLevel;
			}
		}

		public function unRegisterd() : void
		{
			SceneManager.getInstance().removeUpdate(this, registerdLevel);
		}

		public function get isRegisterd() : Boolean
		{
			return false;
		}

		/**
		 * 更新间隔
		 */
		public function get frameInterval() : uint
		{
			return _frameInterval;
		}

		/**
		 * @private
		 */
		public function set frameInterval(value : uint) : void
		{
			_frameInterval = value;
			checkUpdateable = true;
		}

		public function destroy() : void
		{
			_isDestroy = true;
		}

		/**
		 * 是否销毁
		 */
		public function get isDestroy() : Boolean
		{
			return _isDestroy;
		}


	}
}